package com.example.api.util;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

/**
 * @Description: HttpRequestUtil
 * @Author: mingtian
 * @CreateDate: 2020/6/15 10:11
 * @Version: 1.0
 */
@Component
public class HttpRequestUtil {

    private final static Logger LOGGER = LoggerFactory.getLogger(HttpRequestUtil.class);

    private static final String pre_address = "http://";

    @Autowired
    private RestTemplate restTemplate;

    /**
     * @param serviceId    注册到eureka的serviceId
     * @param uri          请求路径（端口后面一段路径 ，如: http:127.0.0.1:8080/aaa/bbb，uri就是aaa/bbb，注意前面不要加"/"）
     * @param data         请求参数
     * @param responseType 返回值类型
     * @param token        token
     * @param <T>
     * @return
     */
    public <T> T post(String serviceId, String uri, Object data, Class<T> responseType, String token) {
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept-Charset", MediaType.APPLICATION_JSON.toString());
        headers.add("token", token);
        HttpEntity<Object> object = new HttpEntity<>(data, headers);
        String url = pre_address + serviceId + "/" + uri;
        LOGGER.info(">>>>>> requestInfo url:{},param:{}", url, JSONObject.toJSONString(object));
        ResponseEntity<T> responseEntity = restTemplate.postForEntity(url, object, responseType);
        LOGGER.info(">>>>>> responseResult  statusCode:{},responseBody:{}", responseEntity.getStatusCode(), responseEntity.getBody());
        return responseEntity.getBody();
    }
}